﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; 
using Microsoft.JCI.Dal;
using System.Data;
using Microsoft.JCI.Common.Entity;
using Microsoft.JCI.Common.Utility; 
using System.Transactions;

namespace Microsoft.JCI.Bll
{
    /// <summary>
    /// 系统管理业务逻辑
    /// </summary>
    public class SystemBll:BllBase
    {
        public SystemBll()
        {
            _cacheName = DeclareHelper.CacheKeysConstant.DictionaryAllCacheKey;
        }

        #region Role Bussiness
        /// <summary>
        /// 保存角色信息以及该角色的权限列表
        /// </summary>
        /// <param name="entity"></param>
        public void SaveRole(SysRoleEntity entity)
        {
            SysRoleDal RoldDal = new SysRoleDal();
            SysRoleFunctionRelationDal RoleFunDal = new SysRoleFunctionRelationDal();

            using (var tran = new System.Transactions.TransactionScope())
            {
                RoldDal.InsertOrUpdate(entity);

                if (entity.RoleFunctionRelateList != null)
                {
                    List<SqlDbParameter> parms = new List<SqlDbParameter>();
                    SqlDbParameter parm = new SqlDbParameter();
                    parm.ColumnName = "RoleID"; parm.ColumnType = DbType.Guid; parm.ParameterName = "@RoleID"; parm.ParameterValue = entity.RoleID; parm.QualificationType = SqlDbParameter.QualificationSymbol.Equal;
                    parms.Add(parm);
                    RoleFunDal.Delete<SysRoleFunctionRelationEntity>(parms);
                    foreach (SysRoleFunctionRelationEntity RoleFunEntity in entity.RoleFunctionRelateList)
                    {
                        RoleFunDal.Insert(RoleFunEntity);
                    }
                }
                tran.Complete(); 
            }
        }

        #endregion

        #region Function Bussiness
        /// <summary>
        /// 根据角色构造功能点树
        /// </summary>
        /// <param name="RoleID"></param>
        /// <returns></returns>
        public DataTable BuildAllFunction(Guid RoleID)
        {
            SysFunctionDal dal = new SysFunctionDal();
            return dal.BuildAllFunction(RoleID);
        }

        /// <summary>
        /// 获取功能点树数据
        /// </summary>
        /// <param name="UserID"></param>
        /// <returns></returns>
        public List<SysFunctionEntity> LoadTreeFunctionEntitiesByUserID(Guid UserID)
        {
            SysFunctionDal dal = new SysFunctionDal();
            return dal.LoadTreeFunctionEntitiesByUserID(UserID);
        }
        #endregion

        #region User Bussiness
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="OldPassword">加密后的旧密码</param>
        /// <param name="NewPassword"></param>
        /// <returns></returns>
        public OperateResult ChangePassword(SysUserEntity entity,string OldPassword, string NewPassword)
        {
            OperateResult result = new OperateResult();
            //检查旧密码是否相同
            if (entity.Password != OldPassword)
            {
                result.ErrorCode = OperateStatus.ToViewError;
                result.ErrorMessage = "旧密码不正确!";
                return result;
            }
            SysUserDal dal = new SysUserDal();
            try
            {
                dal.UpdatePassword(entity.UserID, NewPassword);
                 
            }
            catch(Exception ex)
            {
                result.ErrorCode = OperateStatus.ToViewError;
                result.ErrorMessage = "保存过程中发生错误!";
 
              
            }
            return result;
        }

        /// <summary>
        /// 检查用户是否具有某权限
        /// </summary>
        /// <param name="UserID">用户ID</param>
        /// <param name="CheckType">0: by URL,  1: by FunctionCode </param>
        /// <param name="CheckObject">Url or FunctionCode</param>
        /// <returns></returns>
        public bool CheckUserHasFuction(Guid UserID, int CheckType, string CheckObject)
        {
            SysFunctionDal FunDal = new SysFunctionDal();
            List<SysFunctionEntity> Funcs = FunDal.LoadUserHavedFunction(UserID);
            if (CheckType == 0)
            {
               return Funcs.Exists(delegate(SysFunctionEntity entity) { return entity.URL.ToLower() == CheckObject.ToLower(); });
            }
            else
            {
                return Funcs.Exists(delegate(SysFunctionEntity entity) { return entity.FuncID.ToLower() == CheckObject.ToLower(); });
            } 
        }

        /// <summary>
        /// 保存用户信息以及该用户的角色列表
        /// </summary>
        /// <param name="entity"></param>
        public void SaveUser(SysUserEntity entity)
        {
            SysUserDal UserDal = new SysUserDal();
            SysUserRoleRelationDal UserRoleDal = new SysUserRoleRelationDal();
             

            using (var tran = new System.Transactions.TransactionScope())
            {
                UserDal.InsertOrUpdate(entity);

                if (entity.UserRoleRelationList != null)
                {
                    //角色
                    List<SqlDbParameter> parms = new List<SqlDbParameter>();
                    SqlDbParameter parm = new SqlDbParameter();
                    parm.ColumnName = "UserID"; parm.ColumnType = DbType.Guid; parm.ParameterName = "@UserID"; parm.ParameterValue = entity.UserID; parm.QualificationType = SqlDbParameter.QualificationSymbol.Equal;
                    parms.Add(parm);
                    UserRoleDal.Delete<SysUserRoleRelationEntity>(parms);
                    foreach (SysUserRoleRelationEntity UserRoleEntity in entity.UserRoleRelationList)
                    {
                        UserRoleDal.Insert(UserRoleEntity);
                    }

                }

                tran.Complete(); 
            }
        }

 
        #endregion

        #region Dictionary Bussiness
        public List<SysDictionaryEntity> GetAllDictionaryFromCache()
        {
            string CacheName = "GetAllDictionary";

            if (base.ExistsCacheData(CacheName))
            {
                return GetCacheData(CacheName) as List<SysDictionaryEntity>;
            }
            else
            {
                SysDictionaryDal dal = new SysDictionaryDal();
                List<SysDictionaryEntity> list = dal.GetAll<SysDictionaryEntity>("");

                AddCache(CacheName, list);

                return list;
            }

        }

        public SysDictionaryEntity GetDictionaryFromCache(Guid ID)
        {
            string CacheName = "GetAllDictionary";
            if (base.ExistsCacheData(CacheName))
            {
                List<SysDictionaryEntity> list = null;
                list = GetCacheData(CacheName) as List<SysDictionaryEntity>;

                return list.Find(delegate(SysDictionaryEntity e) { return e.DictionaryId == ID; });
            }
            else
            {
                SysDictionaryDal dal = new SysDictionaryDal();
                return dal.Get<SysDictionaryEntity>(ID);
            }
        }

        public SysDictionaryEntity GetDictionaryFromCache(string Code)
        {
            string CacheName = "GetAllDictionary";
            if (base.ExistsCacheData(CacheName))
            {
                List<SysDictionaryEntity> list = null;
                list = GetCacheData(CacheName) as List<SysDictionaryEntity>;

                return list.Find(delegate(SysDictionaryEntity e) { return e.Code == Code; });
            }
            else
            {
                SysDictionaryDal dal = new SysDictionaryDal();
                return dal.Get<SysDictionaryEntity>(" and Code = '"+Code+"'");
            }
        }

        public List<SysDictionaryEntity> GetDictionaryListFromCache(Enumerator.DictionaryType type)
        {
            string CacheName = "GetAllDictionary";
            if (base.ExistsCacheData(CacheName))
            {
                List<SysDictionaryEntity> list = null;
                list = GetCacheData(CacheName) as List<SysDictionaryEntity>;

                return list.FindAll(delegate(SysDictionaryEntity e) { return e.DictionaryType ==(int)type; });
            }
            else
            {
                SysDictionaryDal dal = new SysDictionaryDal();
                List<SysDictionaryEntity> list = dal.GetAll<SysDictionaryEntity>("");

                AddCache(CacheName, list);

                return list.FindAll(delegate(SysDictionaryEntity e) { return e.DictionaryType == (int)type; });
            }
        }

        public List<SysDictionaryEntity> GetDictionaryFromCacheByParentID(Guid ParentID)
        {
            string CacheName = "GetAllDictionary";
            if (base.ExistsCacheData(CacheName))
            {
                List<SysDictionaryEntity> list = null;
                list = GetCacheData(CacheName) as List<SysDictionaryEntity>;

                return list.FindAll(delegate(SysDictionaryEntity e) { return e.ParentId == ParentID; });
            }
            else
            {
                SysDictionaryDal dal = new SysDictionaryDal();
                List<SysDictionaryEntity> list = dal.GetAll<SysDictionaryEntity>("");

                AddCache(CacheName, list);
                return list.FindAll(delegate(SysDictionaryEntity e) { return e.ParentId == ParentID; });
            }
        }

        public SysDictionaryEntity GetDictionaryFromCache(Enumerator.DictionaryType type, string Code)
        {
            string CacheName = "GetAllDictionary";
            if (base.ExistsCacheData(CacheName))
            {
                List<SysDictionaryEntity> list = null;
                list = GetCacheData(CacheName) as List<SysDictionaryEntity>;

                return list.Find(delegate(SysDictionaryEntity e) { return e.DictionaryType == (int)type && e.Code == Code; });
            }
            else
            {
                SysDictionaryDal dal = new SysDictionaryDal();
                List<SysDictionaryEntity> list = dal.GetAll<SysDictionaryEntity>("");

                AddCache(CacheName, list);
                return list.Find(delegate(SysDictionaryEntity e) { return e.DictionaryType == (int)type && e.Code == Code; });
            }
        }
        #endregion

        #region Helper Methods
        public string GetDispatchFormCode()
        {
            Util u = new Util();
            SysAutoCodeRuleEntity entity = u.GetEntity("DispatchCode");
            if (entity != null)
            {
                if (entity.ResetType == 0)
                    return string.Format(entity.RuleFormat, entity.Seed);
                else
                    return string.Format(entity.RuleFormat, DateTime.Now, entity.Seed);
            }

            return string.Empty;
        }
        #endregion


        public DataTable QueryCompanyEntity(List<SqlDbParameter> Conditions)
        {
            SysCompanyDal dal = new SysCompanyDal();
            return dal.QueryCompanyEntity(Conditions);
        }

        public DataTable QueryVendorEntity(List<SqlDbParameter> Conditions)
        {
            SysCompanyDal dal = new SysCompanyDal();
            return dal.QueryVendorEntity(Conditions);
        }

        public void GetAll<T1>()
        {
            throw new NotImplementedException();
        }

        public bool IsAdmin(Guid UserId)
        {
            SysRoleDal dal = new SysRoleDal();
            return dal.IsAdmin(UserId);
        }
        public void SavePower(SysUserEntity entity)
        {
            SysUserDal UserDal = new SysUserDal();
            SysUserRoleRelationDal UserRoleDal = new SysUserRoleRelationDal();
            if (entity.UserRoleRelationList != null)
            {
                //角色
                List<SqlDbParameter> parms = new List<SqlDbParameter>();
                SqlDbParameter parm = new SqlDbParameter();
                parm.ColumnName = "UserID";
                parm.ColumnType = DbType.Guid;
                parm.ParameterName = "@UserID";
                parm.ParameterValue = entity.UserID;
                parm.QualificationType = SqlDbParameter.QualificationSymbol.Equal;
                parms.Add(parm);
                UserRoleDal.Delete<SysUserRoleRelationEntity>(parms);
                foreach (SysUserRoleRelationEntity UserRoleEntity in entity.UserRoleRelationList)
                {
                    UserRoleDal.Insert(UserRoleEntity);
                }

            }
        }
    }
}
